<template>
  <div>
    <div class="search">
      <el-select v-model="type" placeholder="请选择" size="medium">
        <el-option label="全部" :value="'all'"></el-option>
        <el-option label="已发布" :value="3"></el-option>
        <el-option label="正在编辑" :value="2"></el-option>
        <el-option label="未发布" :value="1"></el-option>
      </el-select>

      <el-button size="medium" type="primary" style="float:right;" @click="newImgDialog = true">新增原素材</el-button>
      <el-button size="medium" type="danger" style="float:right;margin-right:5px;" v-show="choosedImgs.length" @click="deleteMate">
        删除选中素材({{choosedImgs.length}})</el-button>
    </div>
    <div class="imgs-content" v-infinite-scroll="loadImgs">
      <el-row v-for="count in Math.ceil(imgs.length / colLimit)" :key="count" :gutter="10">
        <el-col :span="6" v-for="i in colLimit" :key="i">
          <el-card shadow="hover" v-if="imgs[(count - 1) * colLimit + (i - 1)]">
            <div v-if="'demo' in imgs[(count - 1) * colLimit + (i - 1)]">
              <div style="width: 100%; height: 0;background:#E7E7E7;position: relative;padding-bottom: 75%;"></div>
              <div style="width: 75px; height: 0;margin:7% 0;background:#E7E7E7;position: relative;padding-bottom: 11%;float:left;border-radius: 4px">
              </div>
              <div
                style="width: 75px; height: 0;margin:7% 0 7% 10px;;background:#E7E7E7;position: relative;padding-bottom: 11%;float:left;border-radius: 4px">
              </div>
            </div>
            <div v-else>
              <div class="mate" style="position:relative;" @mouseover="imgHover(imgs[(count - 1) * colLimit + (i - 1)].objid)"
                @mouseout="imgMouseOut(imgs[(count - 1) * colLimit + (i - 1)].objid)">
                <el-image @click="imgChoose(imgs[(count - 1) * colLimit + (i - 1)].objid)" :src="imgUrlQ + imgs[(count - 1) * colLimit + (i - 1)].url"
                  fit="fill" lazy>
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div v-show="imgs[(count - 1) * colLimit + (i - 1)].mouseHover" style="position:absolute;bottom:5px;text-align:center;width:100%;">
                  <el-button v-if="imgs[(count - 1) * colLimit + (i - 1)].status == 1" type="primary" round
                    @click="toPublish(imgs[(count - 1) * colLimit + (i - 1)].objid)">发布</el-button>
                  <el-button v-if="imgs[(count - 1) * colLimit + (i - 1)].status == 2" type="primary" round
                    @click="continueEdit(imgs[(count - 1) * colLimit + (i - 1)].objid)">继续编辑</el-button>
                  <el-button v-if="imgs[(count - 1) * colLimit + (i - 1)].status == 3" type="primary" round
                    @click="editTag(imgs[(count - 1) * colLimit + (i - 1)].objid)">修改</el-button>
                </div>
                <div v-show="imgs[(count - 1) * colLimit + (i - 1)].choosed" style="position:absolute;top:10px;right:10px;">
                  <el-button type="success" size="small" icon="el-icon-check" circle></el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div style="text-align:center;padding:10px 10px;" v-show="nomore">
        没有更多了~
      </div>
    </div>
    <el-dialog title="新增原素材" :visible.sync="newImgDialog" width="60%">
      <div style="text-align:center">
        <el-upload :action="`${apiConfig}/front/Material/createMate`" :key="randKey" list-type="picture-card" multiple
          :on-preview="handlePictureCardPreview" :on-success="uploadImgSuccess" :before-upload="beforeImgUpload"
          :headers="{atoken:userMsg.token, aid:userMsg.objid}">
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newImgDialog = false">取 消</el-button>
        <el-button type="primary" @click="newImgDialog = false">完 成</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="showBigImg">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex"
import { apiConfig, imgUrlQ } from "@/api/apiTool"
import { getMateList, deleteMate } from "@/api/front/Material"
import { createTag, getTagByMateObjid } from "@/api/front/tag"
export default {
  data() {
    return {
      type: 'all',
      imgs: [],
      nomore: false,
      nowpage: 1,
      pageLimit: 12,
      colLimit: 4,
      loading: false,
      newImgDialog: false,
      showBigImg: false,
      dialogImageUrl: '',
      uploadImgs: [],
      randKey: 1,
      apiConfig: apiConfig.api,
      imgUrlQ: imgUrlQ,
      choosedImgs: []
    }
  },
  created() {
  },
  computed: {
    ...mapGetters({
      userMsg: 'user/getUserMsg',
    })
  },
  methods: {
    //加载图片
    loadImgs() {
      if (!this.loading && !this.nomore) {
        this.imgs = this.imgs.concat(Array.from(new Array(this.pageLimit), item => { return { demo: true } }));
        let param = {
          page: this.nowpage,
          limit: this.pageLimit,
          type: this.type
        }
        this.loading = true;

        getMateList(param, (res) => {
          this.loading = false
          if (res.code == 200) {

            this.nowpage += 1
            this.imgs = this.imgs.concat(res.data)
            this.imgs = this.imgs.filter(item => !("demo" in item));
            if (res.data.length == 0) {
              this.nomore = true;
              return;
            }
          }
        })
      }
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.showBigImg = true;
    },
    //图片上传前检查
    beforeImgUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    //图片上传成功
    uploadImgSuccess(res, file) {
      this.$message.success("素材上传成功");
      res.data.status = 1;
      this.uploadImgs.push(res.data)
    },
    //选中图片【删除】
    imgChoose(objid) {
      this.imgs = this.imgs.map((item) => {
        if (item.objid == objid) {
          if (item.choosed) {
            item.choosed = false
            this.choosedImgs = this.choosedImgs.filter(item => item != objid)
          }
          else {
            item.choosed = true;
            this.choosedImgs.push(objid);
          }
        }
        return item;
      })
    },
    //删除素材
    deleteMate() {
      this.$confirm('此操作将删除原素材，并且基于该原素材的发布的编辑信息也将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMate({ imgs: this.choosedImgs }, (res) => {
          if (res.code == 200) {
            this.choosedImgs.map((item) => {
              this.imgs = this.imgs.filter(it => it.objid != item)
            })
            this.choosedImgs = []
          }
        }, true)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //鼠标移动
    imgHover(objid) {
      this.imgs = this.imgs.map((item) => {
        if (item.objid == objid) {
          item.mouseHover = true
        }
        return item;
      })
    },
    //鼠标移出
    imgMouseOut(objid) {
      this.imgs = this.imgs.map((item) => {
        if (item.objid == objid) {
          item.mouseHover = false
        }
        return item;
      })
    },
    //去发布
    toPublish(objid) {
      createTag({ objid: objid }, (res) => {
        if (res.code == 200) {
          this.$router.push({
            path: '/publish',
            query: { objid: res.objid }
          })
        }
      })
    },
    //继续编辑
    continueEdit(objid) {
      getTagByMateObjid({ objid: objid }, (res) => {
        if (res.code == 200) {
          this.$router.push({
            path: '/publish',
            query: { objid: res.objid }
          })
        }
      })
    },
    //修改
    editTag(objid) {
      getTagByMateObjid({ objid: objid }, (res) => {
        if (res.code == 200) {
          this.$router.push({
            path: '/publish',
            query: { objid: res.objid }
          })
        }
      })
    }
  },
  watch: {
    'newImgDialog': function (val) {
      if (val == true) {
        this.uploadImgs = []
      }
      else {
        this.randKey = new Date().getTime();
        if (this.uploadImgs.length) {
          if (this.type == 1 || this.type == 'all') {
            this.imgs = this.uploadImgs.reverse().concat(this.imgs)
            this.uploadImgs = []
          }
        }
      }
    },
    'type': function (val) {
      this.nowpage = 1;
      this.loading = false
      this.nomore = false
      this.imgs = []
      this.loadImgs();
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 15px;
}
.imgs-card {
  width: 300px;
}
/deep/ .el-card {
  border: none;
}
/deep/ .el-card__body {
  padding: 10px 10px;
}
.mate:hover {
  cursor: pointer;
}
</style>